package com.mzba.place.ui;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.MenuItem;
import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.R;
import com.mzba.place.db.SafeCardTable;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.RegisterEntity;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;
/**
 * 
 * @author 06peng
 *
 */
public class UserInfoActivity extends BasicActivity implements Callback {
	
	private ImageView avatarImageView;
	private TextView usernameTextView;
	
	private Handler handler;
	
	private final int logout = 6;
	private final int load_avatar = 7;
	private final int check_update = 8;
	private final int check_update_lastest = 9;
	
	private WeakReference<Bitmap> avatarBitmap = null;
	private String updateUrl;
	
	private RelativeLayout receiveLayout;
	private CheckBox cbReceive;
	private TextView tvCheckUpdate;
	private TextView tvContactUs;
	private TextView tvAboutUs;
	private TextView tvUpdateInfo;
	private TextView tvLogout;
	private TextView tvLogout2;
	private RelativeLayout logoutLayout;
	
	private SharedPreferences sp;
	private RegisterEntity entity;
	private String deviceId;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle("用户帐号");
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.user_info);
		usernameTextView = (TextView) findViewById(R.id.username);
		avatarImageView = (ImageView) findViewById(R.id.useravatar);
		receiveLayout = (RelativeLayout) findViewById(R.id.layout_receive_news);
		cbReceive = (CheckBox) findViewById(R.id.cb_receive_message);
		TelephonyManager tm = (TelephonyManager) getSystemService(Activity.TELEPHONY_SERVICE);
		deviceId = tm.getDeviceId();
		sp = getSharedPreferences(AppContext.NOTIfACATION_RECEIVE, Activity.MODE_APPEND);
		boolean isReceive = sp.getBoolean("isReceive", false);
		if (isReceive) {
			cbReceive.setChecked(true);
		} else {
			cbReceive.setChecked(false);
		}
		cbReceive.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Editor e = sp.edit();
				if (cbReceive.isChecked()) {
					e.putBoolean("isReceive", false);
					cbReceive.setChecked(false);
				} else {
					e.putBoolean("isReceive", true);
					cbReceive.setChecked(true);
				}
				e.commit();
				Toast.makeText(UserInfoActivity.this, "设置已保存", Toast.LENGTH_LONG).show();
			}
		});
		receiveLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Editor e = sp.edit();
				if (cbReceive.isChecked()) {
					e.putBoolean("isReceive", false);
					cbReceive.setChecked(false);
				} else {
					e.putBoolean("isReceive", true);
					cbReceive.setChecked(true);
				}
				e.commit();
				
			}
		});
		tvCheckUpdate = (TextView) findViewById(R.id.check_update);
		tvCheckUpdate.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				UICore.eventTask(UserInfoActivity.this, UserInfoActivity.this, check_update, null, true);
			}
		});
		tvContactUs = (TextView) findViewById(R.id.contact_us);
		tvContactUs.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent data = new Intent(UserInfoActivity.this, FeedBackActivity.class);
				startActivity(data);
			}
		});
		tvAboutUs = (TextView) findViewById(R.id.about_us);
		tvAboutUs.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(UserInfoActivity.this, AboutUsActivity.class));
			}
		});
		tvUpdateInfo = (TextView) findViewById(R.id.update_info);
		tvUpdateInfo.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(UserInfoActivity.this, UpdateUserInfoActivity.class));
			}
		});
		avatarImageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(UserInfoActivity.this, UpdateUserInfoActivity.class));
			}
		});
		tvLogout = (TextView) findViewById(R.id.logout_info);
		tvLogout2 = (TextView) findViewById(R.id.logout2_info);
		tvLogout2.setVisibility(View.GONE);
		logoutLayout = (RelativeLayout) findViewById(R.id.logout_info_layout);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		UserTable ut = new UserTable(this);
		entity = ut.get();
		initUser();
		if (StringUtil.isNotBlank(entity.getAvatar_url())) {
			UICore.eventTask(this, this, load_avatar, null, true);
		}
	}
	
	private void initUser() {
		if (StringUtil.isNotBlank(entity.getUsername())) {
			usernameTextView.setText(entity.getUsername());
		}
		if (entity != null) {
			if (StringUtil.isNotBlank(entity.getEmail()) && entity.getUuid().equals(deviceId)) {
				tvUpdateInfo.setText("查看资料");
				tvLogout.setText("用其他账户登录");
//				tvLogout2.setText(entity.getUsername());
			} else if (StringUtil.isNotBlank(entity.getEmail()) && !entity.getUuid().equals(deviceId)) {
				tvUpdateInfo.setText("查看资料");
				tvLogout.setText("注销当前账户");
//				tvLogout2.setText(entity.getUsername());
			} else {
				tvUpdateInfo.setText("完善资料");
				tvLogout.setText("已有账户，去登录");
//				tvLogout2.setText("");
			}
		}
		logoutLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (StringUtil.isNotBlank(entity.getEmail()) && entity.getUuid().equals(deviceId)) {
					startActivity(new Intent(UserInfoActivity.this, LoginActivity.class));
					finish();
				} else if (StringUtil.isNotBlank(entity.getEmail()) && !entity.getUuid().equals(deviceId)) {
					UICore.eventTask(UserInfoActivity.this, UserInfoActivity.this, logout, null, true);
				} else {
					startActivity(new Intent(UserInfoActivity.this, LoginActivity.class));
					finish();
				}
			}
		});
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		}
		return false;
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case load_avatar:
			avatarBitmap = new WeakReference<Bitmap>(Utils.getBitmap(this, entity.getAvatar_url()));
			handler.sendEmptyMessage(load_avatar);
			break;
		case check_update:
			try {
				String response = HttpUtils.doGet(UrlConfig.check_update + "?app=Android");
				if (StringUtil.isNotBlank(response)) {
					if (!response.equals("null")) {
						JSONObject result = new JSONObject(response);
						String buildno = result.getString("buildno");
						updateUrl = result.getString("url");
						int localBuildno = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
						boolean isNum = true;
						int serverBuildno = 0;
						if (StringUtil.isNotBlank(buildno)) {
							try {
								serverBuildno = Integer.parseInt(buildno);
							} catch (Exception e) {
								isNum = false;
							}
						}
						if (isNum && serverBuildno > localBuildno) {
							handler.sendEmptyMessage(check_update);
						} else {
							handler.sendEmptyMessage(check_update_lastest);
						}
					} else {
						handler.sendEmptyMessage(check_update_lastest);
					}
				} else {
					handler.sendEmptyMessage(check_update_lastest);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case logout:
			logout();
			break;
		}
	}
	
	private void logout() {
		try {
			SafeCardTable st = new SafeCardTable(this);
			st.clearTable();
			HashMap<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("uuid", deviceId);
			String response = HttpUtils.doPost(this, UrlConfig.register, paramsMap);
			if (response != null) {
				Gson gson = new Gson();
				RegisterEntity entity = gson.fromJson(response, RegisterEntity.class);
				if (entity != null) {
					String authToken = entity.getAuthentication_token();
					AppContext.getInstance().setAuthToken(authToken);
					UserTable ut = new UserTable(this);
					ut.save(entity);
				}
			} 
			handler.sendEmptyMessage(logout);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case load_avatar:
				avatarImageView.setImageBitmap(avatarBitmap.get());
				break;
			case check_update:
				showChoseMes("检查到有新的版本，确定要下载吗？", check_update);
				break;
			case check_update_lastest:
				setSysMes("当前应用已经是最新版本！");
				break;
			case logout:
				Intent intent = new Intent(this, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		if (what == check_update) {
			if (StringUtil.isNotBlank(updateUrl)) {
				Intent intent = new Intent();        
				intent.setAction("android.intent.action.VIEW");    
				Uri content_url = Uri.parse(updateUrl);   
				intent.setData(content_url);  
				startActivity(intent);
			}
		}
	}
	
	
	
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (avatarBitmap != null && avatarBitmap.get() != null && !avatarBitmap.get().isRecycled()) {
				avatarBitmap.get().recycle();
				avatarBitmap = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
